package ru.passivemoney.manage.job;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.passivemoney.common.UtilsOrders;
import ru.passivemoney.common.UtilsOrders.ActionUnderOrder;
import ru.passivemoney.manage.messages.MessagesHolder;
import ru.passivemoney.manage.orders.OrdersHolder;

import com.dukascopy.api.IOrder;

/**
 * Задача на установку StopLoss
 *
 */
public class JobSL extends Job {
	
	private static final Logger logger = LoggerFactory.getLogger(JobSL.class);
	
	private BigDecimal slPrice;

	public JobSL(IOrder order, BigDecimal slPrice, int slippage) {
		super(order);
		this.slPrice = slPrice;
		logger.info("JobSL id - {}. Creating new Job. Order id - {}, order label - {}, SL price - {}",
				new Object[]{order.getId(), order.getLabel(), slPrice.doubleValue()});
	}

	/**
	 * В результате работы данного метода ордер обязательно должен быть возвращён в список открытых ордеров.
	 */
	@Override
	protected void execute() {
		if(!UtilsOrders.isOrderOpenedOrFilled(order)){
			logger.info("JobSL id - {}. Order is not opened or filled {}", getId(), order.getLabel());
			return;
		}
		
		String key = UtilsOrders.keyForSharedMap(order, ActionUnderOrder.CHANGE);
		MessagesHolder.put(key, null);
		
   		try{
   			logger.info("JobSL id - {}. Try to set new StopLoss for order {}", getId(), order.getLabel());
   			
   			order.setStopLossPrice(slPrice.doubleValue());
    			
   			while(MessagesHolder.get(key) == null){
   				timeCounter += minTimeToWait;
   				if(timeCounter > maxTimeToWait){
   					logger.error("JobSL id - {}. Stop loss error: Message doesn't come! Order {}", getId(), order.getLabel());
   					return;
   				}
   				Thread.sleep(minTimeToWait);
   			}
    			
    	}catch(Exception e){
    		logger.error("JobSL id - {}. Error when set stop loss for order {}", getId(), order.getLabel());
    		logger.error("", e);
    	}finally{
    		OrdersHolder.putToOpenedOrders(order.getInstrument(), order);
    		MessagesHolder.remove(key);
    	}
	}

}
